#include "receiveImage.h"
#include<QHostAddress>
#include<QPixmap>
#include<QImageReader>
#include<QBuffer>


ReceiveImage::ReceiveImage(QWidget *parent) 
{
    start_flag = 1;
    // dstip.setAddress("192.168.62.117");
    dstip.setAddress("127.0.0.1");
}

ReceiveImage::~ReceiveImage()
{
    delete receiver;
}

bool ReceiveImage::init()
{
    if (start_flag)
    {
        receiver = new QUdpSocket(this);
       
        start_flag = 0;
        // 打开 JSON 文件
        QFile file("config.json");
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            qDebug() << "Failed to open JSON file.";
            return 1;
        }
        // 读取 JSON 内容
        QByteArray jsonData = file.readAll();
        file.close();
        // 解析 JSON 数据
        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &error);
        if (jsonDoc.isNull()) {
            qDebug() << "Failed to parse JSON file:" << error.errorString();
            return 1;
        }
        // 检查是否为对象
        if (!jsonDoc.isObject()) {
            qDebug() << "JSON document is not an object.";
            return 1;
        }
        QJsonObject root = jsonDoc.object();
        QJsonArray localArray = root["local"].toArray();
        qDebug() << "local:";
        for(const QJsonValue& value : localArray) {
            qDebug() << value.toString();
        }
        dstip.setAddress(localArray[0].toString());
        receiver->bind(localArray[1].toString().toInt());
    }
    return true;
}

void ReceiveImage::disinit()
{
    /* 解绑，不再监听 */
    receiver->abort();
    this->exit();
}

void ReceiveImage::run()
{
    //对图像进行二次处理再次实现
}

void ReceiveImage::receiveVideo()
{
    while (receiver->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(receiver->pendingDatagramSize());
        QHostAddress sender_address;
        quint16 sender_port;

        // 读取收到的数据包
        receiver->readDatagram(datagram.data(), datagram.size(), &sender_address, &sender_port);
        // qDebug() << "IPv4 Address: " << sender_address.toString();
        //  qDebug() << "Port: " << sender_port;
        // 解析数据包
        qint32 data_length, packet_index,data_type;
        QByteArray image_data;
     
        QDataStream stream(datagram);

        stream >> data_length >> packet_index;

    
        // qDebug() << "data_length=" << data_length;
        // qDebug() << "packet_index=" << packet_index;

        image_data = datagram.mid(sizeof(data_length) + sizeof(packet_index));
        // 处理数据包
        //向上去整，防止少发
        qint32 packet_count = (data_length + packet_unit - 1) / packet_unit;
        // 将图像数据组合起来
        received_data.append(image_data);

        // 如果已经接收到所有数据包，则进行图像重组
        if (packet_index == packet_count)
        {
        // 检查接收到的数据长度是否与期望的一致
            if (received_data.size() == static_cast<int>(data_length))
            {
                // qDebug() << "received_data=" << received_data.size() <<  "data_length=" << data_length;
                // 将 QByteArray 转为 QImage
                QImage reassembled_image;
                reassembled_image.loadFromData(received_data);
                emit sendReceiveImageToWidget(reassembled_image);
                // 在这里可以使用 reassembled_image 进行进一步的处理或者显示
                // qDebug() << "Image reassembled successfully.";
            }
            else
            {
                qDebug() << "Error: Incomplete image data received.";
            }

            // 清空接收缓存
            received_data.clear();
        }
    }
}

